package com.example.demo.http.servlet;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class MyRequest {

    private String url;
    private String method;


    public MyRequest(InputStream is) {

        try {
            byte[] bytes = new byte[is.available()];
            if (bytes.length > 0) {
                IOUtils.readFully(is,bytes);
            }
            String content = new String(bytes, StandardCharsets.UTF_8);
            System.out.println("-------------------");
            System.out.println(content);
            System.out.println("----------------------");
            if (StringUtils.isBlank(content)) {
                return;
            }
            parse(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void parse(String in) {
        String[] lines = in.split("[\r\n]");
        String headLine = lines[0];
        String[] arr = headLine.split(" ");
        if (!Objects.equals(3, arr.length)) {
            return;
        }
        method = arr[2];
        url = arr[1];
    }

    public String getMethod() {
        if (Objects.isNull(method)) {
            return "";
        }
        return this.method;
    }

    public String getUri() {
        if (Objects.isNull(url)) {
            return "";
        }
        return this.url;
    }
}
